<template>
  <div class="demo-content">
    <h1>Fabric.js实现缩放、拖动、旋转</h1>

    <section class="demo-text">
      <canvas id="canvas" width="1200" height="600" ref="canvas"></canvas>
      <h2>移动</h2>
      <p>
        Fabric.js已经封装了Window的event事件，拖动用到的事件为鼠标按下（'mouse:down'）、鼠标抬起（'mouse：up'）、鼠标移动（'mouse：move'）
        <br />使用
        <span class="annotation">canvas.on(event,function)</span> 来为图层添加监听事件
        <br />
        <img src="~@/imags/move.png" alt />
      </p>
      <h2>缩放</h2>
      <p>
        为canvas添加鼠标滚轮事件，使用
        <span class="annotation">canvas.getzoom()</span> 来获取当前层级，计算出新的层级和当前鼠标位置
        <br />使用
        <span class="annotation">canvas.zoomToPoint(zoomPoint, zoom)</span> 实现根据鼠标中心点缩放
        <br />
        <img src="~@/imags/scal.png" alt />
      </p>
      <p style="text-align:right;padding-right:60px">@王睿杰 2019.1.18</p>
    </section>
  </div>
</template>
<script>
import { fabric } from "@/js/fabric";
export default {
  mounted() {
    var canvas;

    //是否拖动
    var panning = false;
    this.$nextTick(() => {
      canvas = new fabric.Canvas("canvas");
      var rect1 = new fabric.Rect({
        top: 50,
        left: 50,
        width: 70,
        height: 70,
        fill: "red",
        label: "ccccc"
      });
      canvas.add(rect1);
      var rect2 = new fabric.Rect({
        top: 50,
        left: 150,
        width: 70,
        height: 70,
        fill: "red"
      });
      canvas.add(rect2);
      var rect3 = new fabric.Rect({
        top: 50,
        left: 250,
        width: 70,
        height: 70,
        fill: "red"
      });

      canvas.add(rect3);
      canvas.add(
        new fabric.Rect({
          top: 0,
          left: 0,
          width: 4,
          height: 4,
          fill: "blue"
        })
      );
      //鼠标按下
      canvas.on("mouse:down", function(e) {
        console.log(e);
        //按住alt键才可拖动画布
        if (e.e.altKey) {
          panning = true;
          canvas.selection = false;
        }
      });
      //鼠标抬起
      canvas.on("mouse:up", function(e) {
        panning = false;
        canvas.selection = true;
      });

      //鼠标移动
      canvas.on("mouse:move", function(e) {
        if (panning && e && e.e) {
          var delta = new fabric.Point(e.e.movementX, e.e.movementY);
          canvas.relativePan(delta);
        }
      });

      //鼠标滚轮监听
      canvas.on("mouse:wheel", function(e) {
        event.preventDefault(); //阻止事件冒泡
        var zoom = (event.deltaY < 0 ? 0.1 : -0.1) + canvas.getZoom();
        zoom = Math.max(0.1, zoom); //最小为原来的1/10
        zoom = Math.min(3, zoom); //最大是原来的3倍
        var zoomPoint = e.pointer;
        canvas.zoomToPoint(zoomPoint, zoom);
      });
    });
  }
};
</script>


